package com.df.twod_sync_bakend.game.scripts;

import com.alibaba.fastjson2.JSON;
import com.df.twod_sync_bakend.game.GameRoom;
import com.df.twod_sync_bakend.game.IScript;
import com.df.twod_sync_bakend.game.MsgTypes;
import com.df.twod_sync_bakend.game.msgs.Msg_Login_Req;
import com.df.twod_sync_bakend.game.msgs.Msg_Login_Resp;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.Arrays;
import java.util.Random;

@Component
public class LoginScript implements IScript<Msg_Login_Req> {
    @Override
    public String getType() {
        return "Login";
    }

    @Override
    public Msg_Login_Req unserialize(String msgStr) {
        if(msgStr!=null){
            return JSON.parseObject(msgStr, Msg_Login_Req.class);
        }
        return null;
    }


    @Override
    public void handle(WebSocketSession session, Msg_Login_Req req, GameRoom room) {
        String uid = req.getUid();
        if(uid==null||uid.isEmpty()){
            room.sendFailMsg(session,getType(),null );
            return;
        }
        // 为新玩家分配随机位置
        float x = new Random().nextFloat() * 840-420;
        float y = new Random().nextFloat() * 720-360;
        // 检查是否已经登录
        if (!room.addPlayer(uid,x,y,session)) {
            room.sendFailMsg(session, getType(), "该用户已登录");
            return;
        }
        //广播给其他玩家

        room.broadCastExclude(Arrays.asList(uid), MsgTypes.EnterRoom,null);
        Msg_Login_Resp msgLoginResp = new Msg_Login_Resp()
                .setUid(uid)
                .setX(x)
                .setY(y);
        // 发送登录成功响应
        room.sendMsg(uid,getType(), msgLoginResp);
    }


}
